
package net.alpcontrol.bi.bootstrap.exception;

import net.alpcontrol.bi.bootstrap.bean.Message;
import net.alpcontrol.bi.bootstrap.utils.AlpNetUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class AlpGlobalExceptionHandler implements HandlerExceptionResolver {
    public AlpGlobalExceptionHandler() {
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        Message message;
        if(ex == null) {
            message = this.handleException(ex);
        } else if(ex instanceof MethodArgumentNotValidException) {
            message = this.handleMethodArgumentNotValidException(ex);
        } else if(ex instanceof HttpMessageNotReadableException) {
            message = this.handleHttpMessageNotReadableException(ex);
        } else if(ex instanceof HttpMediaTypeNotSupportedException) {
            message = this.handleHttpMediaTypeNotSupportedException(ex);
        } else if(ex instanceof AlpException) {
            message = this.handleHHException(ex);
        } else {
            message = this.handleException(ex);
        }

        AlpNetUtils.writeJson(response, message);
        return null;
    }

    private Message handleMethodArgumentNotValidException(Exception e) {
        MethodArgumentNotValidException ex = (MethodArgumentNotValidException)e;
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        return errors.size() > 0? Message.failure(((ObjectError)errors.get(0)).getDefaultMessage()):Message.failure("无效的参数");
    }

    private Message handleHttpMessageNotReadableException(Exception e) {
        return Message.failure("参数不能为空");
    }

    private Message handleHttpMediaTypeNotSupportedException(Exception e) {
        return Message.failure("不支持的内容类型");
    }

    private Message handleHHException(Exception e) {
        AlpException ex = (AlpException)e;
        return Message.failure(ex.getCode(), ex.getMessage(), (Object)null);
    }

    private Message handleException(Exception e) {
        e.printStackTrace();
        return Message.failure("操作失败");
    }
}
